<template>
  <div>
    <van-calendar
      color="#009B63"
      :style="{ height: '450px' }"
      v-model="showDate"
      :max-date="maxDate"
      :min-date="minDate"
      :default-date="defaultDate"
      :formatter="formatter"
      :show-confirm="false"
      @confirm="onConfirm"
    />
    <div class="busDeMessage">
      <div class="busDetailNav">{{ serviceTypeName }}日期选择</div>
      <div>
        <div class="busTopText">
          <div style="color: #1A1A1A; font-size: 16px; font-weight: bold;">{{ fullname }}</div>
          <div style="color: #999;font-size: 12px;margin-top: 3px;">{{ address }}</div>
        </div>
      </div>
      <div class="busDateTime">
        <div
          class="busHave"
          v-for="(item, index) in dataArray"
          :key="index"
          :class="showFlag == index ? (item.reserve != 0 ? 'busHaveClick' : 'nobusHaveClick') : ''"
          @click="chooseDay(index, item)"
        >
          <div :class="{ color2C85FE: item.week == '今日' }">{{ item.week }}</div>
          <div :class="{ color2C85FE: item.week == '今日' }">{{ item.month + 1 + '月' + item.day + '日' }}</div>
          <div
            style="padding-bottom: 3px;"
            :style="
              item.reserve != 0 ? (showFlag == index ? 'color:#fff;background:#FFAE00' : 'color:#FFAE00') : 'color:#999'
            "
          >
            {{ item.week == '今日'?(todayreserve== 0 ? '约满' : '余号' + todayreserve):(item.canlave ? (item.reserve == 0 ? '约满' : '余号' + item.reserve) : '无号' )}}
          </div>
        </div>
        <div class="busSelect">
          <img style="width: 100%;" src="~@/assets/images/regAllSelet.png" alt="" />
          <span style="width: 8%;position: absolute;right: 6px;" @click="showDate = !showDate">
            全部日期
          </span>
        </div>
      </div>
    </div>
    <div class="busDetContent" v-if="workDayTimeMorning.length + workDayTimeAfternoon.length > 0">
      <div class="signSource" v-if="workDayTimeMorning.length > 0">
        <div class="signTitle">
          <img style="width: 20px;margin-right: 8px;" src="~@/assets/images/regamSign.png" alt="" /> 上午号源
        </div>
        <!-- 循环 约满变色-->
        <div class="signList" v-for="(item, index) in workDayTimeMorning" :key="index" @click="toSure(item)">
          <span style="font-size: 14px;display: inline-block;width: 60%;">{{ item.intervalBeginTime }}-{{ item.intervalEndTime }}</span>
          <div style="display:inline-block">
            <span style="color:#999;margin-right:32px;line-height: 27px;">预约 {{ item.lave }}</span>
            <span class="signSy" :class="item.workreserve == 0 ? 'nosignSyColor' : 'signSyColor'">
              {{ item.workreserve == 0 ? '约满' : '剩余&nbsp;' + item.workreserve }}
            </span>
          </div>
        </div>
      </div>
      <!-- 下午号源 -->
      <div class="signSource" style="margin-top:13px;" v-if="workDayTimeAfternoon.length > 0">
        <div class="signTitle">
          <img style="width: 20px;margin-right: 8px;" src="~@/assets/images/regpmSign.png" alt="" /> 下午号源
        </div>
        <!-- 循环 约满变色-->
        <div class="signList" v-for="(item, index) in workDayTimeAfternoon" :key="index" @click="toSure(item)">
          <span style="font-size: 14px;display: inline-block;width: 60%;">{{ item.intervalBeginTime }}-{{ item.intervalEndTime }}</span>
          <div style="display:inline-block">
            <span style="color:#999;margin-right:32px;line-height: 27px;">预约 {{ item.lave }}</span>
            <span class="signSy" :class="item.workreserve == 0 ? 'nosignSyColor' : 'signSyColor'">
              {{ item.workreserve == 0 ? '约满' : '剩余&nbsp;' + item.workreserve }}
            </span>
          </div>
        </div>
      </div>
      <div style="height: 16px;"></div>
    </div>
    <!-- 无号显示 -->
    <div class="busNoData" v-else>
      <img style="width: 66%;margin-left: 17%;padding-top: 80px;" src="~@/assets/images/regnoData.png" alt="" />
      <div style="font-size: 12px;color: #999;text-align: center;padding-bottom: 55%;">
        当天无号，请查看其它日期号源
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import '../../style/reservaIndex_index.css';
import 'vant/lib/toast/style';
import 'vant/lib/calendar/style';
import { Toast, Calendar, Dialog} from 'vant';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { cloudApi } from '@/api/indexApi';
import Header from '@/components/Header.vue';
Vue.use(Calendar);
Vue.use(Toast);
Vue.use(Dialog);
Component.registerHooks(['beforeRouteUpdate', 'beforeRouteLeave', 'beforeRouteLeave', 'created']);
@Component({
  components: { Header, Calendar },
})
export default class BusinessDetail extends Vue {
  departId: any = ''; // 网点部门id
  customerName: any = ''; // 客户姓名
  customerPhone: any = ''; // 客户手机号
  serviceType: any = ''; //预约业务类别
  serviceTypeName: any = ''; //预约业务类别
  address: any = '';
  fullname: any = '';
  openId: any = '';
  intervalSeriNo: string = '';
  reserveDate: string = ''; //预约日期
  intervalBeginTime: string = ''; //预约时间
  intervalEndTime: string = '';
  workDays: Array<any> = [];
  workDayTimeMorning: Array<any> = [];
  workDayTimeAfternoon: Array<any> = [];
  showOnebusDate: boolean = true;
  dataArray: Array<any> = []; //上部显示的日期数组
  dataArray1: Array<any> = []; //日历中显示的日期数组
  showDate: boolean = false;
  minDate: any = new Date();
  maxDate: any = null;
  defaultDate: any = new Date();
  showFlag: number = 0; //点击样式
  dayLength: number = 0;
  reserve: any = '';
  workDayTime: Array<any> = [];
  todayreserve: any = '';
  Morning: Array<any> = [];
  Afternoon: Array<any> = [];
  today:Array<any> = [];
  latitude:any = '';
  longitude:any = '';
  created() {
    document.title = '网点预约'
    this.departId = this.$route.query.departId; // 网点部门id
    this.customerName = this.$route.query.customerName; // 客户姓名
    this.customerPhone = this.$route.query.customerPhone; // 客户手机号
    this.serviceType = this.$route.query.serviceType; //预约业务类别
    this.address = this.$route.query.address;
    this.fullname = this.$route.query.fullname;
    this.longitude = this.$route.query.longitude; 
    this.latitude= this.$route.query.latitude;


    this.openId = this.$route.query.openId;
    if(this.$route.query.serviceType == '01'){
      this.serviceTypeName = '承保';
    } else if(this.$route.query.serviceType == '02'){
      this.serviceTypeName = '理赔';
    }
    var date = new Date();
    if (date.getDay() == 0 || date.getDay() == 6) {
      this.maxDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 9);
      this.dayLength = 10;
    } else {
      this.maxDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 8);
      this.dayLength = 9;
    }
  }
  mounted() {
    this.createDateArray();
    this.queryTime();
  }
  formatter(day: any) {
    const month = day.date.getMonth();
    const date = day.date.getDate();
    for (var i = 0; i < this.dataArray1.length; i++) {
      if (month == new Date().getMonth() && date == new Date().getDate()) {
        day.text = '今日';
        if (!this.dataArray1[i].canlave) {
          day.bottomInfo = '无号';
          day.className = 'gray';
          break;
        } else if (this.dataArray1[i].todayreserve == 0) {
          day.bottomInfo = '约满';
          day.className = 'gray';
          break;
        } else {
          day.bottomInfo = '余号' + this.dataArray1[i].todayreserve;
          day.className = 'yellow';
          break;
        }
      }
      if (month == this.dataArray1[i].month && date == this.dataArray1[i].day) {
        if (!this.dataArray1[i].canlave) {
          day.bottomInfo = '无号';
          day.className = 'gray';
          break;
        } else if (this.dataArray1[i].reserve == 0) {
          day.bottomInfo = '约满';
          day.className = 'gray';
          break;
        } else {
          day.bottomInfo = '余号' + this.dataArray1[i].reserve;
          day.className = 'yellow';
          break;
        }
      }
    }
    return day;
  }
  onConfirm(date: any) {
    var _this = this;
    _this.showDate = false;
    var day = date.getDate();
    var month = date.getMonth();
    var year = date.getFullYear();
    _this.dataArray1.forEach(function(ele: any, index: any) {
      if (ele.day == day && ele.month == month && ele.year == year) {
        _this.reserveDate = ele.year + '-' + (ele.month + 1) + '-' + ele.day;
        _this.chooseDay(index, ele);
      }
    });
  }
  createDateArray() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth();
    var day = date.getDate();
    var weekArr = ['日', '一', '二', '三', '四', '五', '六'];
    this.dataArray = [];
    this.dataArray1 = [];
    for (var i = 0; i < this.dayLength; i++) {
      var obj = {};
      if (i == 0) {
        (obj as any).week = '今日';
      } else {
        (obj as any).week = '周' + weekArr[new Date(year, month, day + i).getDay()];
      }
      (obj as any).year = new Date(year, month, day + i).getFullYear();
      (obj as any).month = new Date(year, month, day + i).getMonth();
      (obj as any).day = new Date(year, month, day + i).getDate();

      (obj as any).reserve = 0; //余号量
      (obj as any).canlave = false; //是否可以预约，不能预约的显示无号
      (obj as any).todayreserve = 0;
      if (i < 5) {
        this.dataArray.push(obj);
      }
      this.dataArray1.push(obj);
    }
  }
  // 查询预约时间日期
  queryTime() {
    // Toast.loading({
    //   duration: 0,
    //   message: '加载中...',
    //   forbidClick: true,
    // });
    var _this = this;
    cloudApi
      .getBookingVolume({
        departId: this.departId,
      })
      .then(function(res: any) {
        // Toast.clear();
        if(res.data.code=='0000'){
          if (res.data && res.data.bookingVolume && res.data.bookingVolume.workDays) {
            var workDays = res.data.bookingVolume.workDays;
            _this.getDayLength(workDays[workDays.length - 1].workDay);
            _this.workDays = workDays;
            _this.dataArray1.forEach(function(ele: any, i: any) {
              _this.workDays.forEach(function(elem: any, idx: any) {
                var workDayTime = elem.workDayTime;
                _this.workDayTime = workDayTime;
                var sum = 0;
                _this.workDayTime.forEach(function(eles: any) {
                var datasplit = elem.workDay.split('-');
                if (
                  ele.year == datasplit[0] &&
                  ele.month + 1 == Number(datasplit[1]) &&
                  ele.day == Number(datasplit[2])
                ) {
                  sum += +eles.workreserve;
                  ele.reserve = sum;
                  ele.canlave = true;
                  if (i < 5) {
                    Vue.set(_this.dataArray, i, ele);
                  }
                  Vue.set(_this.dataArray1, i, ele);
                }
                if (idx == _this.workDays.length - 1) {
                  _this.maxDate = new Date(datasplit[0], Number(datasplit[1]) - 1, datasplit[2]);
                }
                });
              });
            });
            _this.chooseDay(0, _this.dataArray1[0]);
          }
        }else{
            Dialog.confirm({
              title: '温馨提示',
              message: res.data.message,
              confirmButtonColor: '#009B63',
            })
            return;          
        }
      });
  }
  getDayLength(endDate: any) {
    var nowDate = new Date();
    var endDatesplit = endDate.split('-');
    var time =
      new Date(endDatesplit[0], endDatesplit[1] - 1, endDatesplit[2]) -
      new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate());
    this.dayLength = time / (24 * 60 * 60 * 1000) + 1;
    this.createDateArray();
  }
  chooseDay(index: any, item: any) {
    var _this = this;
    _this.showFlag = index;
    _this.workDayTimeMorning = [];
    _this.workDayTimeAfternoon = [];
    _this.Morning= [];
    var month = item.month + 1;
    var itemDate =
      item.year + '-' + (month < 9 ? '0' + month : month) + '-' + (item.day < 10 ? '0' + item.day : item.day);
    _this.reserveDate = itemDate;
    if (item.canlave) {
      // 当天如果时间区间是2点半到3点,三点以后才不显示
      let nowhour = new Date().getHours();
      let nowMinutes = new Date().getMinutes();
      let laterHour = nowhour  < 10 ? '0'+ nowhour: nowhour;
      let laterTime = laterHour + ':' + (nowMinutes < 10 ? '0'+ nowMinutes: nowMinutes)
      _this.workDays.forEach(function(elem: any) {
        if (itemDate == elem.workDay) {
          elem.workDayTime.forEach(function(ele: any, i: any) {
            if (ele.intervalEndTime <= '12:00') {
              if(item.week == '今日'){
                if(ele.intervalEndTime > laterTime){
                  _this.workDayTimeMorning.push(ele);
                  _this.Morning.push(ele.workreserve);
                }
              }else {
                _this.workDayTimeMorning.push(ele);
              }
            } else {
              if(item.week == '今日'){
              if(ele.intervalEndTime > laterTime){
                  _this.workDayTimeAfternoon.push(ele);
                  _this.Morning.push(ele.workreserve);
                }
              }else {
                _this.workDayTimeAfternoon.push(ele);
              }
            }
          });
        }
      });
    }
          var num = 0;
          _this.Morning.forEach(function(e: any) {
            num += +e;
            _this.todayreserve = num;
            _this.dataArray1[0].todayreserve=_this.todayreserve
        });
  };
  toSure(item: any) {
    if (item.workreserve <= 0) {
      return;
    }
    var _this = this;
    this.$router.push({
      path: 'registerSure',
      query: {
        departId: _this.departId,
        customerName: _this.customerName,
        customerPhone: _this.customerPhone,
        serviceType: _this.serviceType,
        intervalSeriNo: item.intervalSeriNo,
        reserveDate: _this.reserveDate,
        intervalBeginTime: item.intervalBeginTime, //预约时间
        intervalEndTime: item.intervalEndTime,
        address: _this.address,
        fullname: _this.fullname,
        openId: _this.openId,
        longitude: this.longitude,
        latitude: this.latitude,
      },
    });
  }
}
</script>
<style lang="less" scoped></style>
